package com.cwj.mylibrary;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;

/**
 * 获取应用版本名称和版本号
 */
public class AppVersionNameAndCode {

    /**
     * 获取当前App版本号
     */
    public static String getVersionName(Context context) {
        String versionName = null;
        PackageManager pm = context.getPackageManager();
        PackageInfo info;
        try {
            info = pm.getPackageInfo(context.getApplicationContext().getPackageName(), 0);
            if (info != null) {
                versionName = info.versionName;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 获取当前App版本Code
     */
    public static long getVersionCode(Context context) {
        long versionCode = 0;
        PackageManager pm = context.getPackageManager();
        PackageInfo info;
        try {
            info = pm.getPackageInfo(context.getApplicationContext().getPackageName(), 0);
            if (info != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    //大于等于9.0系统获取版本号
                    versionCode = info.getLongVersionCode();
                } else {
                    //小于9.0系统获取版本号
                    versionCode = info.versionCode;
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }
}
